<!--
  头像组件，无图片或加载失败显示图像占位符
  src           ====>     头像地址
  name          ====>     人员姓员
  width         ====>     头像宽度，如30px
  height        ====>     头像高度，如30px
  fontSize      ====>     姓名文字
-->
<template>
  <template v-if="showImage">
    <s-image :src="src" :width="width" :height="height" :border-radius="width" @error="onError"></s-image>
  </template>
  <div class="s-avatar base-flex base-align-items-center base-justify-content-center" :style="{width: width, height: height, borderRadius: width, fontSize: fontSize}" v-else>
      {{ showName }}
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '40px'
  },
  height: {
    type: String,
    default: '40px'
  },
  fontSize: {
    type: String,
    default: '18px'
  }
})

const showImage = ref(true)
const showName = ref('')

watch(() => props.name, (curr, old) => {
  showName.value = processName(curr)
})

onMounted(() => {
  showName.value = processName(props.name)
  // console.log(showName.value)
  // console.log(showImage.value)
})

const processName = ((str) => {
  if (str.length === 2) {
    return str.charAt(0);
  } else if (str.length > 2) {
    return str.slice(-2);
  } else {
    return str;
  }
})
const onError = (e) => {
  if(e.type === 'error') {
    console.log('加载失败', e)
    showImage.value = false
  }
  // console.log(e)
}
</script>

<style lang="scss" scoped>
.s-avatar {
  background: $primaryColor;
  color: #ffffff;
}
</style>
